package com.v.im.gatewayservice.service;

import com.v.im.commonmodule.utils.bean.CurrentUserInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.server.ServerWebExchange;

/**
 * @author wym
 * @create 2019-03-12 9:28
 **/
@Slf4j
@Component
public class UserAuthService {

    private final static String TOKEN_VALUE = "access_token";

    @Autowired
    RestTemplate restTemplate;

    public CurrentUserInfo getUserInfoByAuth(String token) {
        CurrentUserInfo currentUserInfo = new CurrentUserInfo();
        try{
            ResponseEntity   responseEntity = restTemplate.getForEntity(
                    ("http://auth-service/oauth/user?access_token="+token), CurrentUserInfo.class);
            currentUserInfo = (CurrentUserInfo) responseEntity.getBody();
        }catch (Exception e){
            log.error("调用用户验证服务失败！！！");
        }
        return currentUserInfo;
    }

    /**
     * 解析token
     *
     * @param content
     * @return
     */
    public String getPostToken(String content) {
        String[] aa = content.trim().split("\"access_token\"");
        String result = aa[1].replaceAll("\r|\n", "");
        String[] asd = result.split("------");
        return asd[0];
    }

    public String getTokenValue(ServerWebExchange exchange) {
        String resToken = "";
        //从get获取
        String token = exchange.getRequest().getQueryParams().getFirst(TOKEN_VALUE);
        if (StringUtils.isNotBlank(token)) {
            resToken = token;
        }
        //从post获取
        Object requestBody = exchange.getAttribute("cachedRequestBodyObject");
        if (requestBody != null && StringUtils.isNotBlank(requestBody.toString())) {
            resToken = getPostToken(requestBody.toString());
        }
        return resToken;
    }

}
